/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include <QMap>
#include <QMenu>
#include <QSound>
#include <QTimer>
#include <QSysInfo>
#include <QSettings>
#include <QTcpSocket>
#include <QScrollBar>
#include <QMessageBox>
#include <QCloseEvent>
#include <QMessageBox>
#include <QInputDialog>
#include <QDesktopWidget>
#ifdef SYS_ANDROID
#include <QAndroidJniObject>
#endif
#include <KMsgFw11Q>
#include "frmChat.h"
#include "frmMenu.h"
#include "frmLogin.h"
#include "frmProfile.h"
#include "frmChangePassword.h"
#include "frmContactRequests.h"
#include "ui_frmLogin.h"
QMap<QString,QListWidgetItem*> stringLinkContact;
QMap<QListWidgetItem*,QString> contactLinkString;
QMap<QString,QObject*> stringLinkChat;
QMap<QString,QString> stringLinkNick;
QMap<QString,QString> stringLinkState;
QAction *logoutPerm;
QAction *logoutTemp;
QAction *setOnline;
QAction *setAway;
QAction *setBusy;
QAction *setNotjust;
QAction *setShowoffline;
QAction *addContact;
QAction *editProfile;
QAction *changePassword;
QAction *seperator1;
QAction *seperator2;
QString myNickname;
QStringList frList;
bool isLoggedIn = false;
bool isSayIC = false;
int frLength;
int ustate;
KMsgFw11Q fw;

QString IncomingMessage = "im";
QString KeppeMessenger = "km";
QString Disconnected = "dc";
QString Reconnected = "rc";
QString LoggedOut = "lo";

frmLogin::frmLogin(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmLogin)
{
    ui->setupUi(this);
    ui->cbStayLoggedIn->setText("Stay logged in");
    ui->swTabs->setCurrentIndex(0);
    ui->cmdFix->setVisible(false);
    QTimer::singleShot(1,this,SLOT(on_timerSS_tick()));
    QTimer::singleShot(30000,this,SLOT(on_timerOA_tick()));
    QTimer::singleShot(10000,this,SLOT(on_timerLC_tick()));
    QTimer::singleShot(275000,this,SLOT(on_timerFR_tick()));
    QSettings settings("Keppe","Keppe Messenger");
    settings.beginGroup("Login");
    bool autologin = settings.value("Autologin",false).toBool();
    QString autoname = QString::fromUtf8(QByteArray::fromHex(QByteArray::fromBase64(settings.value("Name","").toString().toUtf8())));
    QString autopassword = QString::fromUtf8(QByteArray::fromHex(QByteArray::fromBase64(settings.value("Password","").toString().toUtf8())));
    settings.endGroup();
    if (autologin)
    {
        ui->txtName->setText(autoname);
        ui->txtPassword->setText(autopassword);
        ui->cbStayLoggedIn->setChecked(true);
        loginUserDataFromLines(false);
    }
    globY = 0;
}

frmLogin::~frmLogin()
{
    delete ui;
}

void frmLogin::logoutUserWithRemoveAutologin()
{
    QSettings settings("Keppe","Keppe Messenger");
    settings.beginGroup("Login");
    settings.setValue("Autologin",false);
    settings.remove("Name");
    settings.remove("Password");
    settings.endGroup();
    logoutUser();
}

void frmLogin::logoutUser()
{
    fw.logoutUser();
    isLoggedIn = false;
    ui->txtName->clear();
    ui->txtName->setFocus();
    ui->txtPassword->clear();
    ui->cbStayLoggedIn->setChecked(false);
    ui->swTabs->setCurrentIndex(0);
    ui->lwContacts->clear();
    setOnline->deleteLater();
    setAway->deleteLater();
    setBusy->deleteLater();
    setNotjust->deleteLater();
    setShowoffline->deleteLater();
    seperator1->deleteLater();
    addContact->deleteLater();
    editProfile->deleteLater();
    changePassword->deleteLater();
    seperator2->deleteLater();
    logoutPerm->deleteLater();
    logoutTemp->deleteLater();
    foreach(QObject *object, stringLinkChat.values())
    {
        frmChat* cw = (frmChat*)object;
        cw->close();
    }
}

void frmLogin::loginUserDataFromLines(bool showErrors)
{
    qDebug() << "Before Login";
    int ret = fw.loginUser(ui->txtName->text(),ui->txtPassword->text());
    qDebug() << "After Login";
    if (ret == 200)
    {
        if (ui->cbStayLoggedIn->isChecked())
        {
            QSettings settings("Keppe","Keppe Messenger");
            settings.beginGroup("Login");
            settings.setValue("Autologin",true);
            settings.setValue("Name",QString::fromUtf8(ui->txtName->text().toUtf8().toHex().toBase64()));
            settings.setValue("Password",QString::fromUtf8(ui->txtPassword->text().toUtf8().toHex().toBase64()));
            settings.endGroup();
        }
        else
        {
            QSettings settings("Keppe","Keppe Messenger");
            settings.beginGroup("Login");
            settings.setValue("Autologin",false);
            settings.remove("Name");
            settings.remove("Password");
            settings.endGroup();
        }
        isLoggedIn = true;
        ui->swTabs->setCurrentIndex(1);
        ui->lwContacts->setFocus();
        myNickname = fw.getUserNick();
        ui->labWelcomeNick->setText(QString("Welcome ") + myNickname + " (<a href=\"kmp://editprofile\">Edit Profile</a>)");
        QString contactsString = fw.getUserContactsWithStates();
        if (contactsString.left(8) != "///Error")
        {
            QStringList contactList = contactsString.split("\n");
            if (contactList.length() >= 1)
            {
                foreach (const QString &contact,contactList)
                {
                    QStringList contactQIL = contact.split("|");
                    if (contactQIL.length() >= 4)
                    {
                        QListWidgetItem *contactItem = new QListWidgetItem(contactQIL.at(1) + "\n" + QString::fromUtf8(fromMessage(contactQIL.at(2))));
                        int contactState = QVariant(contactQIL.at(3)).toInt();
                        contactItem->setIcon(QIcon(getIconPathForOnlineState(contactState)));
                        stringLinkContact[contactQIL.at(0)] = contactItem;
                        stringLinkNick[contactQIL.at(0)] = contactQIL.at(1);
                        stringLinkState[contactQIL.at(0)] = contactQIL.at(2);
                        contactLinkString[contactItem] = contactQIL.at(0);
                        ui->lwContacts->addItem(contactItem);
                    }
                }
            }
        }
        updateFriendRequests();
        setOnline = ui->menuMessenger->addAction("Online",this,SLOT(setStateOnline()));
        setAway = ui->menuMessenger->addAction("Away",this,SLOT(setStateAway()));
        setBusy = ui->menuMessenger->addAction("Busy",this,SLOT(setStateBusy()));
        setNotjust = ui->menuMessenger->addAction("Not just",this,SLOT(setStateNotjust()));
        setShowoffline = ui->menuMessenger->addAction("Show offline",this,SLOT(setStateShowoffline()));
        seperator1 = ui->menuMessenger->addSeparator();
        addContact = ui->menuMessenger->addAction("Add contact",this,SLOT(addContactShow()));
        editProfile = ui->menuMessenger->addAction("Edit Profile",this,SLOT(editProfileShow()));
        changePassword = ui->menuMessenger->addAction("Change password",this,SLOT(changePasswordShow()));
        seperator2 = ui->menuMessenger->addSeparator();
        logoutPerm = ui->menuMessenger->addAction("Logout (Perm)",this,SLOT(logoutUserWithRemoveAutologin()));
        logoutTemp = ui->menuMessenger->addAction("Logout (Exit, Temp)",this,SLOT(endKM()));
    }
    else if (ret == 404)
    {
        if (showErrors) {QMessageBox::information(this,"Keppe Messenger","You have type invalid account data!");}
    }
    else if (ret == 500)
    {
        if (showErrors) {QMessageBox::information(this,"Keppe Messenger","Can't connect to Keppe Messenger Server");}
    }
}

void frmLogin::setStateOnline()
{
    fw.setUserOnlineState(1);
}

void frmLogin::setStateAway()
{
    fw.setUserOnlineState(2);
}

void frmLogin::setStateBusy()
{
    fw.setUserOnlineState(3);
}

void frmLogin::setStateNotjust()
{
    fw.setUserOnlineState(4);
}

void frmLogin::setStateShowoffline()
{
    fw.setUserOnlineState(5);
}

void frmLogin::openLoginWindowNormal()
{
    this->adjustSize();
    this->showMaximized();
    this->activateWindow();
}

void frmLogin::closeEvent(QCloseEvent *event)
{
    if (isLoggedIn)
    {
        int ret = QMessageBox::question(this,"Keppe Messenger","Logout (Exit, Temp)?",QMessageBox::Yes,QMessageBox::No);

        if (ret == QMessageBox::Yes)
        {
            foreach(QObject *object, stringLinkChat.values())
            {
                frmChat* cw = (frmChat*)object;
                cw->close();
            }
            event->accept();
        }
        else
        {
            event->ignore();
        }
    }
    else
    {
        foreach(QObject *object, stringLinkChat.values())
        {
            frmChat* cw = (frmChat*)object;
            cw->close();
        }
        event->accept();
    }
}

void frmLogin::endKM()
{
    this->close();
}

QString frmLogin::getIconPathForOnlineState(int id)
{
    if (id == 1)
    {
        return ":/img/online-t2x64.png";
    }
    if (id == 2)
    {
        return ":/img/away-t2x64.png";
    }
    if (id == 3)
    {
        return ":/img/busy-t2x64.png";
    }
    if (id == 4)
    {
        return ":/img/notjust-t1x64.png";
    }
    if (id == 5)
    {
        return ":/img/showoffline-t1x64.png";
    }
    if (id == 8)
    {
        return ":/img/offline-t1x64.png";
    }
    return ":/img/offline-t1x64.png";
}

QString frmLogin::getOnlineStateStringFromID(int id)
{
    if (id == 1)
    {
        return "Online";
    }
    if (id == 2)
    {
        return "Away";
    }
    if (id == 3)
    {
        return "Busy";
    }
    if (id == 4)
    {
        return "Not just";
    }
    if (id == 5)
    {
        return "Show offline";
    }
    if (id == 8)
    {
        return "Offline";
    }
    return "Offline";
}

void frmLogin::on_timerFR_tick()
{
    if (fw.isLoggedIn())
    {
        updateFriendRequests();
    }
    QTimer::singleShot(275000,this,SLOT(on_timerFR_tick()));
}

void frmLogin::on_timerSS_tick()
{
    if (fw.isLoggedIn())
    {
        if (fw.isObjectIncoming())
        {
            QString readstr = fw.readObject();
            if (readstr != "")
            {
                QStringList readstrlist = readstr.split("<>");
                if (readstrlist.length() >= 1)
                {
                    if (readstrlist.at(0) == "MessageFromUser")
                    {
                        if (readstrlist.length() >= 2)
                        {
                            QStringList msg = readstrlist.at(1).split(":");
                            QString username;
                            if (msg.length() >= 1)
                            {
                                username = msg.at(0);
                            }
                            QString message;
                            int len = 17+username.length()+1;
                            if (readstr.length() >= len)
                            {
                                message = readstr.remove(0,len);
                            }
                            message = message.trimmed();
                            if (username.trimmed() == "" || message.trimmed() == "")
                            {
                                //Error
                            }
                            else
                            {
                                if (!stringLinkChat.contains(username))
                                {
                                    if (stringLinkNick.contains(username) && stringLinkState.contains(username))
                                    {
                                        openChatWindow(username,stringLinkNick[username],stringLinkState[username],true);
                                    }
                                    else
                                    {
                                        openChatWindow(username,username,"(She/He is not your friend)",true);
                                    }
                                }
                                frmChat *cw = (frmChat*)stringLinkChat[username];
                                cw->incomingMessage(message);
                                if (cw->isMinimized() || !cw->isActiveWindow() || cw->isHidden())
                                {
                                    if (stringLinkNick.contains(username))
                                    {
                                        notification(stringLinkNick[username] + ": " + QString::fromUtf8(fromMessage(message)),KeppeMessenger);
                                    }
                                    else
                                    {
                                        notification(username + ": " + QString::fromUtf8(fromMessage(message)),KeppeMessenger);
                                    }
                                }
                            }
                        }
                    }
                    else if (readstrlist.at(0) == "ReturnIntialize")
                    {
                        int id = 0;
                        QString users;
                        QString action;
                        QString request;
                        QString username;
                        QString notification;
                        foreach(QString argstr,readstrlist)
                        {
                            if (argstr.left(5) == "--at=")
                            {
                                action = argstr.remove(0,5).replace("&nbsp;"," ").replace("&amp;","&");
                            }
                            if (argstr.left(5) == "--rq=")
                            {
                                request = argstr.remove(0,5).replace("&nbsp;"," ").replace("&amp;","&");
                            }
                            if (argstr.left(5) == "--nt=")
                            {
                                notification = argstr.remove(0,5).replace("&nbsp;"," ").replace("&amp;","&");
                            }
                            if (argstr.left(5) == "--id=")
                            {
                                id = QVariant(argstr.remove(0,5)).toInt();
                            }
                            if (argstr.left(8) == "--users=")
                            {
                                users = argstr.remove(0,8).replace("&nbsp;"," ").replace("&amp;","&").replace("&lt;&gt;","\n");
                            }
                            if (argstr.left(11) == "--username=")
                            {
                                username = argstr.remove(0,11).replace("&nbsp;"," ").replace("&amp;","&").replace("&lt;&gt;","\n");
                            }
                            if (request == "contactsrequests" && id == 200)
                            {
                                QStringList friendList = users.split("\n");
                                friendList.removeAll("");
                                friendList.removeAll("\r");
                                friendList.removeAll("\n");
                                friendList.removeAll("\r\n");
                                if (friendList.length() >= 1)
                                {
                                    frList = friendList;
                                    updateWelcomeLabel(myNickname);
                                }
                                else
                                {
                                    frList.clear();
                                    updateWelcomeLabel(myNickname);
                                }
                            }
                            else if (action == "sendmessage" && id == 200)
                            {
                            }
                        }
                    }
                }
            }
        }
    }
    QTimer::singleShot(1,this,SLOT(on_timerSS_tick()));
}

void frmLogin::on_timerOA_tick()
{
    if (fw.isLoggedIn())
    {
        QString contactsString = fw.getUserContactsWithStates();
        if (contactsString.left(8) != "///Error")
        {
            QStringList contactList = contactsString.split("\n");
            if (contactList.length() >= 1)
            {
                foreach (const QString &contact,contactList)
                {
                    QStringList contactQIL = contact.split("|");
                    if (contactQIL.length() >= 4)
                    {
                        if (stringLinkContact.contains(contactQIL.at(0)))
                        {
                            QListWidgetItem *contactItem = stringLinkContact[contactQIL.at(0)];
                            int contactState = QVariant(contactQIL.at(3)).toInt();
                            contactItem->setIcon(QIcon(getIconPathForOnlineState(contactState)));
                            contactItem->setText(contactQIL.at(1) + "\n" + QString::fromUtf8(fromMessage(contactQIL.at(2))));
                            stringLinkNick[contactQIL.at(0)] = contactQIL.at(1);
                            stringLinkState[contactQIL.at(0)] = contactQIL.at(2);
                        }
                        else
                        {
                            QListWidgetItem *contactItem = new QListWidgetItem(contactQIL.at(1) + "\n" + QString::fromUtf8(fromMessage(contactQIL.at(2))));
                            int contactState = QVariant(contactQIL.at(3)).toInt();
                            contactItem->setIcon(QIcon(getIconPathForOnlineState(contactState)));
                            stringLinkContact[contactQIL.at(0)] = contactItem;
                            stringLinkNick[contactQIL.at(0)] = contactQIL.at(1);
                            stringLinkState[contactQIL.at(0)] = contactQIL.at(2);
                            contactLinkString[contactItem] = contactQIL.at(0);
                            ui->lwContacts->addItem(contactItem);
                        }
                    }
                }
            }
        }
    }
    QTimer::singleShot(30000,this,SLOT(on_timerOA_tick()));
}

void frmLogin::on_timerLC_tick()
{
    if (isLoggedIn)
    {
        if (!fw.isLoggedIn())
        {
            int ret = fw.loginUser(ui->txtName->text(),ui->txtPassword->text());
            if (ret == 200)
            {
                ui->labWelcomeNick->setText("Welcome " + fw.getUserNick() + " (<a href=\"kmp://editprofile\">Edit Profile</a>)");
                if(isSayIC)
                {
                    notification("Keppe Messenger has relogged in your account",KeppeMessenger);
                    isSayIC = false;
                }
            }
            else if (ret == 404)
            {
                isLoggedIn = false;
                logoutUser();
                notification("Your Account data has been expired!",KeppeMessenger);
            }
            else if (ret == 500)
            {
                if(!isSayIC)
                {
                    notification("Please check your Internet connection!",KeppeMessenger);
                    isSayIC = true;
                }
            }
        }
    }
    QTimer::singleShot(10000,this,SLOT(on_timerLC_tick()));
}

void frmLogin::updateFriendRequests()
{
    fw.requestGetUserFriendRequests();
}

void frmLogin::updateFriendRequestList(QString toAdd, QString toRemove)
{
    if (toAdd != "")
    {
        frList.append(toAdd);
        frList.sort();
        frLength++;
    }
    if (toRemove != "")
    {
        frList.removeAll(toRemove);
        frLength--;
    }
    updateWelcomeLabel(myNickname);
}

void frmLogin::on_cmdLogin_clicked()
{
    loginUserDataFromLines(true);
}

void frmLogin::on_lwContacts_itemDoubleClicked(QListWidgetItem *item)
{
    if (contactLinkString.contains(item))
    {
        QString uname = contactLinkString[item];
        QStringList ulist = item->text().split("\n");
        openChatWindow(uname,ulist.at(0),ulist.at(1));
    }
}

void frmLogin::openChatWindow(QString username, QString nickname, QString userstate, bool minimized)
{
    if (!stringLinkChat.contains(username))
    {
        frmChat *c = new frmChat();
        stringLinkChat[username] = c;
        c->setChatter(username,nickname,userstate,myNickname,true);
        c->setForm(this);
        if (minimized == true)
        {
        }
        else
        {
            c->adjustSize();
            c->showMaximized();
            c->activateWindow();
        }
    }
    else
    {
        frmChat *cw = (frmChat*)stringLinkChat[username];
        cw->adjustSize();
        cw->showMaximized();
        cw->activateWindow();
    }
}

int frmLogin::addUserContact(QString username)
{
    return fw.addUserContact(username);
}

int frmLogin::delUserContact(QString username)
{
    return fw.delUserContact(username);
}

int frmLogin::sendMessage(QString username, QString message)
{
    int ret = fw.sendMessageToUser(username,message);
    return ret;
}

int frmLogin::setUserPassword(QString oldpassword, QString newpassword)
{
    int ret = fw.setUserPassword(oldpassword,newpassword);
    return ret;
}

int frmLogin::setUserNick(QString nick)
{
    int ret = fw.setUserNick(nick);
    return ret;
}

int frmLogin::setUserMessageState(QString message)
{
    int ret = fw.setUserMessageState(message);
    return ret;
}

void frmLogin::updateWelcomeLabel(QString nick)
{
    myNickname = nick;
    if (frLength == 1)
    {
        ui->labWelcomeNick->setText("Welcome " + myNickname + " (<a href=\"kmp://editprofile\">Edit Profile</a>)<br>You have 1 (<a href=\"kmp://friendrequests\">Friend Request</a>)");
    }
    else if (frLength >= 2)
    {
        ui->labWelcomeNick->setText("Welcome " + myNickname + " (<a href=\"kmp://editprofile\">Edit Profile</a>)<br>You have " + QString::number(frLength) + " (<a href=\"kmp://friendrequests\">Friend Requests</a>)");
    }
    else
    {
        ui->labWelcomeNick->setText("Welcome " + myNickname + " (<a href=\"kmp://editprofile\">Edit Profile</a>)");
    }
}

void frmLogin::removeMe(QString username)
{
    stringLinkChat.remove(username);
}

void frmLogin::on_cmdClose_clicked()
{
    this->close();
}

void frmLogin::on_lwContacts_itemClicked(QListWidgetItem *item)
{
    on_lwContacts_itemDoubleClicked(item);
}

void frmLogin::on_cmdFix_clicked()
{
    ui->txtPassword->setEchoMode(QLineEdit::Normal);
    ui->cmdFix->setVisible(false);
}

void frmLogin::addContactItem(QString username)
{
    QListWidgetItem *contactItem = new QListWidgetItem(username + "\n");
    int contactState = 8;
    contactItem->setIcon(QIcon(getIconPathForOnlineState(contactState)));
    stringLinkContact[username] = contactItem;
    stringLinkNick[username] = username;
    stringLinkState[username] = contactState;
    contactLinkString[contactItem] = username;
    ui->lwContacts->addItem(contactItem);
    if (stringLinkChat.contains(username))
    {
        frmChat *cw = (frmChat*)stringLinkChat[username];
        cw->setChatter(username,username,"",myNickname);
    }
}

void frmLogin::addContactShow()
{
    QString input;
    QString ainput;
    int ret;
readdcontact:
    input = QInputDialog::getText(this,"Add contact","Please type in the account name of your contact",QLineEdit::Normal,"",0,windowFlags()^Qt::WindowMinMaxButtonsHint);
    if (input != "")
    {
        ainput = toAccountName(input.toUtf8());
        ret = fw.addUserContact(ainput);
        if (ret == 200)
        {
            addContactItem(ainput);
        }
        else if (ret == 404)
        {
            QMessageBox::information(this,"Keppe Messenger","The account " + input + " don't exists!");
            goto readdcontact;
        }
        else
        {
            QMessageBox::warning(this,"Keppe Messenger","Add contact failed!");
        }
    }
}

void frmLogin::addContactOverMenu(QObject* menu)
{
    QString input;
    QString ainput;
    int ret;
readdcontact:
    input = QInputDialog::getText((frmMenu*)menu,"Add contact","Please type in the account name of your contact",QLineEdit::Normal,"",0,windowFlags()^Qt::WindowMinMaxButtonsHint);
    if (input != "")
    {
        ainput = toAccountName(input.toUtf8());
        ret = fw.addUserContact(ainput);
        if (ret == 200)
        {
            addContactItem(ainput);
        }
        else if (ret == 404)
        {
            QMessageBox::information((frmMenu*)menu,"Keppe Messenger","The account " + input + " don't exists!");
            goto readdcontact;
        }
        else
        {
            QMessageBox::warning((frmMenu*)menu,"Keppe Messenger","Add contact failed!");
        }
    }
}

void frmLogin::removeContactShow()
{
    if (contactLinkString.contains(ui->lwContacts->currentItem()))
    {
        QString username = contactLinkString[ui->lwContacts->currentItem()];
        int ret = QMessageBox::question(this,"Keppe Messenger","Are you sure to remove " + stringLinkNick[username] + " from your Contacts?",QMessageBox::Yes, QMessageBox::No);
        if (ret == QMessageBox::Yes)
        {
            if (fw.delUserContact(username) == 200)
            {
                QListWidgetItem *citem = stringLinkContact[username];
                contactLinkString.remove(citem);
                if (stringLinkChat.contains(username))
                {
                    frmChat* cw = (frmChat*)stringLinkChat[username];
                    cw->close();
                    stringLinkChat.remove(username);
                }
                stringLinkContact.remove(username);
                stringLinkNick.remove(username);
                stringLinkState.remove(username);
                delete citem;
            }
            else
            {
                QMessageBox::warning(this,"Keppe Messenger","Can't remove " + stringLinkNick[username] + " from your Contacts.");
            }
        }
    }
}

QString frmLogin::toAccountName(QByteArray account)
{
    QString text = QString::fromUtf8(account);
    text.replace(QString::fromUtf8("&"),"&amp;");
    text.replace(QString::fromUtf8("<"),"&lt;");
    text.replace(QString::fromUtf8(">"),"&gt;");
    text.replace(QString::fromUtf8("\""),"&quot;");
    text.replace(QString::fromUtf8("ä"),"&auml;");
    text.replace(QString::fromUtf8("ö"),"&ouml;");
    text.replace(QString::fromUtf8("ü"),"&uuml;");
    text.replace(QString::fromUtf8("Ä"),"&Auml;");
    text.replace(QString::fromUtf8("Ö"),"&Ouml;");
    text.replace(QString::fromUtf8("Ü"),"&Uuml;");
    text.replace(QString::fromUtf8("ß"),"&szlig;");
    text.replace(QString::fromUtf8("€"),"&euro;");
    text.replace(QString::fromUtf8("§"),"&sect;");
    text.replace(QString::fromUtf8("©"),"&copy;");
    text.replace(QString::fromUtf8("®"),"&reg;");
    text.replace(QString::fromUtf8("°"),"&deg;");
    text.replace(QString::fromUtf8("²"),"&sup2;");
    text.replace(QString::fromUtf8("³"),"&sup3;");
    text.replace(QString::fromUtf8("\r\n"),"<br>");
    text.replace(QString::fromUtf8("\r"),"<br>");
    text.replace(QString::fromUtf8("\n"),"<br>");
    return text;
}

QByteArray frmLogin::fromMessage(QString message)
{
    QByteArray text = message.toUtf8();
    text.replace("&auml;","ä");
    text.replace("&ouml;","ö");
    text.replace("&uuml;","ü");
    text.replace("&Auml;","Ä");
    text.replace("&Ouml;","Ö");
    text.replace("&Uuml;","Ü");
    text.replace("&szlig;","ß");
    text.replace("&euro;","€");
    text.replace("&sect;","§");
    text.replace("&copy;","©");
    text.replace("&reg;","®");
    text.replace("&deg;","°");
    text.replace("&sup2;","²");
    text.replace("&sup3;","³");
    text.replace("<br>","\n");
    text.replace("&quot;","\"");
    text.replace("&lt;","<");
    text.replace("&gt;",">");
    text.replace("&amp;","&");
    return text;
}

void frmLogin::on_labWelcomeNick_linkActivated(const QString &link)
{
    if (link == "kmp://menu")
    {
        QString messageState = fw.getUserMessageState();
        QString contactsLength = fw.getUserContactsLength();
        if (messageState.left(8) == "///Error") {messageState = "";}
        if (contactsLength.left(8) == "///Error") {contactsLength = "";}
        frmMenu *fm = new frmMenu();
        fm->setForm(this);
        fm->setData(ui->txtName->text(),myNickname,messageState,contactsLength);
        fm->adjustSize();
        fm->showMaximized();
    }
    if (link == "kmp://editprofile")
    {
        QString messageState = fw.getUserMessageState();
        QString contactsLength = fw.getUserContactsLength();
        if (messageState.left(8) == "///Error") {messageState = "";}
        if (contactsLength.left(8) == "///Error") {contactsLength = "";}
        frmProfile* pe = new frmProfile();
        pe->setForm(this);
        pe->setData(ui->txtName->text(),myNickname,messageState,contactsLength);
        pe->adjustSize();
        pe->showMaximized();
    }
    if (link == "kmp://friendrequests")
    {
        frmContactRequests *fr = new frmContactRequests();
        fr->setForm(this);
        fr->setContacts(frList);
        fr->showMaximized();
    }
}

void frmLogin::notification(QString text, QString method)
{
#ifdef SYS_ANDROID
    QAndroidJniObject javaNotification = QAndroidJniObject::fromString(text);
    QAndroidJniObject::callStaticMethod<void>("org/keppe/msg/KeppeMessenger",
                                              QString("notify" + method).toStdString().c_str(),
                                              "(Ljava/lang/String;)V",
                                              javaNotification.object<jstring>());
    QSound::play(":/sound/ChatIn.wav");
#else
    Q_UNUSED(text);
    Q_UNUSED(method);
#endif
}

void frmLogin::playChatIn()
{
#if QT_VERSION >= 0x050000
    if (QFile::exists("ChatIn.wav"))
    {
        QSound::play("ChatIn.wav");
    }
    else
    {
        if (QFile::copy(":/sound/ChatIn.wav","ChatIn.wav")) {QSound::play("ChatIn.wav");}
    }
#else
    //if (isPhonon)
    //{
    //    Phonon::MediaObject *player = Phonon::createPlayer(Phonon::CommunicationCategory, Phonon::MediaSource(":/sound/ChatIn.wav"));
    //    player->play();
    //}
    //else
    //{
    if (QFile::exists("ChatIn.wav"))
    {
        QSound::play("ChatIn.wav");
    }
    else
    {
        if (QFile::copy(":/sound/ChatIn.wav","ChatIn.wav")) {QSound::play("ChatIn.wav");}
    }
#endif
    // }
}

bool frmLogin::isConnectedWithServer()
{
    if (isLoggedIn)
    {
        if (fw.isLoggedIn())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

void frmLogin::editProfileShow()
{
    QString messageState = fw.getUserMessageState();
    QString contactsLength = fw.getUserContactsLength();
    if (messageState.left(8) == "///Error") {messageState = "";}
    if (contactsLength.left(8) == "///Error") {contactsLength = "";}
    frmProfile* pe = new frmProfile();
    pe->setForm(this);
    pe->setData(ui->txtName->text(),myNickname,messageState,contactsLength);
    pe->adjustSize();
    pe->showMaximized();
}

void frmLogin::changePasswordShow()
{
    frmChangePassword *cp = new frmChangePassword();
    cp->setForm(this);
    cp->adjustSize();
    cp->showMaximized();
}

void frmLogin::on_lwContacts_mouseMove(QMouseEvent *ev)
{
    ev->accept();
}
